module.exports = Behavior({
    data: {
        // host: 'https://www.mayihuatuan.com',
        host: 'https://flower.yunhuajie.com',
        // imgHost: 'https://img.mayihuatuan.com/',
        imgHost: 'https://cdn.yunhuajie.com/',
        userInfo: null,
        allow_jump: true, //为false时不可跳转至登录，节流 防止多次跳转
    },
    pageLifetimes: {
        show: function () {
            const userInfo = getApp().globalData.userInfo;
            if (userInfo) {
                //用户未完善手机号，强制完善手机号
                // if (userInfo.audit === 0 && !this.data.dontShowTipModal) {
                //     wx.showModal({
                //         content: '请先授权手机号！',
                //         confirmColor: '#188075',
                //         showCancel: false,
                //         success(res) {
                //             wx.switchTab({ url: '/pages/my/index' })
                //         }
                //     })
                // }
                this.setData({
                    userInfo,
                });
            } else {
                let Authorization = wx.getStorageSync('Authorization');
                if (Authorization) this.getUserInfo();
            }
        },
    },
    methods: {
        //隐藏弹窗通用方法
        hide_popup({ currentTarget }) {
            let obj = {};
            obj[currentTarget.dataset.field] = false;
            this.setData(obj);
        },
        /**显示弹窗通用方法 */
        show_popup(e) {
            let obj = {};
            obj[e.currentTarget.dataset.field] = true;
            this.setData(obj);
        },
        //401重定向登录
        redirect_login(scene) {
            if (!this.data.allow_jump) return;
            this.data.allow_jump = false;
            getApp().globalData.userInfo = null;
            this.setData({ userInfo: null, buttonLoading: false });
            wx.removeStorageSync('Authorization');
            wx.stopPullDownRefresh();
            this.wxLogin(scene);
        },
        //微信授权登录
        wxLogin(scene) {
            let that = this;
            wx.login({
                //获取code
                withCredentials: true,
                timeout: 10000,
                success(res) {
                    let reqData = { code: res.code };
                    if (scene) reqData.invite_id = scene;
                    that.request(
                        {
                            url: '/api/login',
                            login: false,
                            loadingTip: '授权中',
                            data: reqData,
                        },
                        ({ data }) => {
                            wx.setStorageSync('Authorization', data.access_token);
                            let options = '';
                            options = that.getCurrentPageUrlWithArgs();
                            delete options.uid;
                            delete options.scene;
                            that.getUserInfo((data) => {
                                that.login_reload(options);
                                if (data.is_auth === 0) that.getUserProfile(options);
                            });
                        }
                    );
                },
            });
        },
        /**获取用户头像、昵称 */
        getUserProfile(options) {
            let that = this;
            wx.showModal({
                title: '提示',
                content: '请允许获取您的昵称、头像',
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#188075',
                success(res) {
                    res.confirm &&
                        wx.getUserProfile({
                            desc: '展示个人头像、昵称', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                            success: ({ userInfo }) => {
                                wx.showLoading({
                                    title: '授权中',
                                    mask: true,
                                });
                                that.request(
                                    {
                                        url: '/api/user/face',
                                        method: 'POST',
                                        hideFailToast: true,
                                        data: {
                                            face: userInfo.avatarUrl,
                                            nickname: userInfo.nickName,
                                        },
                                    },
                                    () => {
                                        that.getUserInfo(that.login_reload(options));
                                    },
                                    null,
                                    () => {
                                        wx.hideLoading();
                                    }
                                );
                            },
                        });
                    that.data.allow_jump = true;
                },
            });
        },
        //登录重载方法
        login_reload(options) {
            wx.hideLoading();
            this.onLoad(options);
            this.onShow();
        },
        //获取当前页面的参数
        getCurrentPageUrlWithArgs() {
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            return currentPage.options;
        },
        //获取用户信息
        getUserInfo(callback) {
            this.request({ url: '/api/user/info' }, ({ data }) => {
                let userInfo = {
                    uid: data.uid,
                    mobile: data.mobile,
                    face: data.face,
                    nickname: data.nickname,
                    is_auth: data.is_auth, //是否微信头像授权[0:未授权,1:已授权]
                    audit: data.audit, //用户注册后手机绑定[0:未绑定,1:已绑定]
                    verify: data.verify, //是否已实名认证[0:未认证,1:已认证]
                    invite_qrcode: data.invite_qrcode,
                    award_percent: data.award_percent, //推荐返佣百分比
                    is_wholesaler: data.is_wholesaler, //是否为批发商用户 0:不是, 1:是
                };
                getApp().globalData.userInfo = userInfo;
                this.setData({ userInfo: userInfo });
                callback && callback(data);
            });
        },
        //wxml点击跳转
        navigator({ currentTarget }) {
            if (currentTarget.dataset.login) {
                let Authorization = wx.getStorageSync('Authorization');
                if (!Authorization) return this.redirect_login();
            }
            wx.navigateTo({ url: currentTarget.dataset.url });
        },
        //延迟执行
        delay(callback, time = 600) {
            let delayTimeId = setTimeout(() => {
                callback();
                clearTimeout(delayTimeId);
            }, time);
        },
        /**
         * 网络请求封装
         * @param {*} req_data
         * url 请求地址,
         * loadingTip:加载中提示，如果存在，先显示loading
         * login:true 需要登录状态
         * @param {*} success_func 成功回调方法
         * @param {*} fail_func 失败回调方法,code 不为零时也会调用
         * @param {*} complete 最终执行的方法
         */
        request: function (req_data, success_func, fail_func = null, complete = null) {
            let that = this;
            let Authorization = wx.getStorageSync('Authorization');
            if (req_data.login !== false) {
                if (!Authorization) {
                    wx.stopPullDownRefresh();
                    that.redirect_login();
                    complete ? complete() : '';
                    return;
                }
            }

            if (req_data.loadingTip) {
                wx.showLoading({
                    title: req_data.loadingTip,
                    mask: true,
                });
            }
            req_data.header = {
                'content-type': 'application/json',
                Accept: 'application/json, text/javascript, */*; q=0.01',
            };

            if (Authorization) req_data.header.Authorization = Authorization;
            req_data.url = this.data.host + req_data.url;

            req_data.success = function (res) {
                //成功处理
                if (res.statusCode == 200) {
                    if (res.header.Authorization) {
                        wx.setStorageSync('Authorization', res.header.Authorization);
                    }
                    let data = res.data;
                    if (data.code === 0) {
                        success_func(data);
                    } else if (data.code == 401) {
                        that.redirect_login();
                    } else if (data.code == 402) {
                        wx.showModal({
                            showCancel: false,
                            content: '您的账号已被禁用，请联系客服',
                            confirmColor: '#188075',
                        });
                    } else {
                        fail_func && fail_func(data);

                        if (req_data.hideDialogCode && req_data.hideDialogCode.includes(data.code)) return;

                        wx.showModal({
                            showCancel: false,
                            content: data.msg || '',
                            confirmColor: '#188075',
                        });
                    }
                } else if (res.statusCode == 401) {
                    that.redirect_login();
                } else if (res.statusCode == 402) {
                    wx.showModal({
                        showCancel: false,
                        content: '您的账号已被禁用，请联系客服',
                        confirmColor: '#188075',
                    });
                } else {
                    fail_func && fail_func(res);
                    wx.showToast({
                        title: res.data.message || res.data || '服务异常',
                        icon: 'none',
                    });
                }
            };
            req_data.fail = function (e) {
                //失败处理
                fail_func
                    ? fail_func(e)
                    : wx.showToast({
                          title: '网络异常：' + e.errMsg || '',
                          icon: 'none',
                      });
            };
            req_data.complete = function (e) {
                //失败处理
                wx.stopPullDownRefresh();
                req_data.loadingTip && wx.hideLoading();
                complete ? complete(e) : '';
            };
            wx.request(req_data);
        },
    },
});
